package com.thinvent.recommend.manager.config;

import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;

/**
 * 单独一个组件：应用启动后检查并创建 ES 索引（含 createTime/updateTime/vec mapping）
 */
@Component
public class ElasticsearchIndexInitializer {

    private final RestClient restClient;
    private final String indexName;

    @Autowired
    public ElasticsearchIndexInitializer(
            RestClient restClient,
            @Value("${elasticsearch.rest.indexName}") String indexName) {
        this.restClient = restClient;
        this.indexName  = indexName;
    }

    @PostConstruct
    public void initIndex() throws IOException {
        // HEAD /{index} 检查索引是否存在
        Request head = new Request("HEAD", "/" + indexName);
        Response headResp = restClient.performRequest(head);
        int status = headResp.getStatusLine().getStatusCode();

        // 构建 mapping JSON：docId、createTime、updateTime、vec（dense_vector + cosine + HNSW）
        String mappingJson =
                "{\n" +
                        "  \"mappings\": {\n" +
                        "    \"properties\": {\n" +
                        "      \"docId\": {\n" +
                        "        \"type\": \"keyword\"\n" +
                        "      },\n" +
                        "      \"createTime\": {\n" +
                        "        \"type\": \"date\",\n" +
                        "        \"format\": \"strict_date_optional_time||epoch_millis\"\n" +
                        "      },\n" +
                        "      \"updateTime\": {\n" +
                        "        \"type\": \"date\",\n" +
                        "        \"format\": \"strict_date_optional_time||epoch_millis\"\n" +
                        "      },\n" +
                        "      \"vec\": {\n" +
                        "        \"type\":       \"dense_vector\",\n" +
                        "        \"dims\":       300,\n" +                          // ← 请根据配置调整 dims
                        "        \"index\":      true,\n" +
                        "        \"similarity\": \"cosine\",\n" +
                        "        \"index_options\": {\n" +
                        "          \"type\":            \"int8_hnsw\",\n" +
                        "          \"m\":               16,\n" +
                        "          \"ef_construction\": 100\n" +
                        "        }\n" +
                        "      }\n" +
                        "    }\n" +
                        "  }\n" +
                        "}";

        if (status == 404) {
            // 索引不存在，连同 mapping 一起创建
            Request create = new Request("PUT", "/" + indexName);
            create.setJsonEntity(mappingJson);
            Response createResp = restClient.performRequest(create);
            int createStatus = createResp.getStatusLine().getStatusCode();
            if (createStatus < 200 || createStatus >= 300) {
                throw new IllegalStateException(
                        "创建 ES 索引失败: " + indexName + ", status: " + createStatus);
            }
        } /*else {
            // 索引已存在，只打 mapping 补丁
            Request patch = new Request("PUT", "/" + indexName + "/_mapping");
            // 只发送 properties 部分即可
            String patchJson = "{ \"properties\": " +
                    mappingJson.substring(mappingJson.indexOf("{", mappingJson.indexOf("\"properties\""))) +
                    "}";
            patch.setJsonEntity(patchJson);
            restClient.performRequest(patch);
        }*/
    }
}
